<?php
/**
 * Joomla! 1.5 component NS Pro
 *
 * @version $Id: nspro.php 2009-04-28 01:47:12 svn $
 * @author Christopher Mavros
 * @package Joomla
 * @subpackage NS Pro
 * @license GNU/GPL
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

class NsproModelSubscribers extends JModel {

    function __construct()
    {
        parent::__construct();

        //global $mainframe, $option;
        $mainframe = JFactory::getApplication();
        $option = JRequest::getCmd('option');
        
        $jversion = new JVersion();
        $this->j15 = ($jversion->RELEASE == '1.5');

        $filter_order     = $mainframe->getUserStateFromRequest(  $option.'filter_order', 'filter_order', 'id', 'cmd' );
        $filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'filter_order_Dir', 'filter_order_Dir', 'asc', 'word' );

        $this->setState('filter_order', $filter_order);
        $this->setState('filter_order_Dir', $filter_order_Dir);

        $array = JRequest::getVar('cid',  0, '', 'array');
        $this->setId((int)$array[0]);
    }

    function setId($id)
    {
        // Set id and wipe data
        $this->_id      = $id;
        $this->_data    = null;
    }

    function getSub()
    {
        $db =& JFactory::getDBO();
        // Load the data
        if (empty( $this->_data )) {
            $query = ' SELECT * FROM `#__nspro_subs` '.
                    '  WHERE `id` = '.$this->_id;
            $db->setQuery( $query );
            $this->_data = $db->loadObject();
        }
        if (!$this->_data) {
            $this->_data = new stdClass();
            $this->_data->id = 0;
            $this->_data->name  = null;
            $this->_data->email = null;
            $this->_data->notes = null;
            $this->_data->datetime = null;
            $this->_data->confirmed = false;
            $this->_data->mailing_lists = null;
        }
        return $this->_data;
    }

    function getSubs($limit, $limitstart, $filterlist) {
        $db =& JFactory::getDBO();

        $query = 'SELECT * FROM `#__nspro_subs` ';
        if ($filterlist == -1) {
          $query = $query . 'WHERE `mailing_lists` = "" ';
        }
        else if ($filterlist > 0) {
          $query = $query . 'WHERE (FIND_IN_SET("'.mysql_escape_string($filterlist).'", `mailing_lists`) > 0) ';
        }
      $orderby = $this->_buildContentOrderBy();
      $query .= $orderby;

        $subs = $this->_getList( $query , $limitstart, $limit);

        return $subs;
    }

    function getSubsSearch($searchstring, $limit, $limitstart, $filterlist) {
      $db =& JFactory::getDBO();

      $query = 'SELECT * FROM `#__nspro_subs` ';
      $query = $query . 'WHERE ((`name` LIKE "%' . mysql_escape_string($searchstring) . '%") OR (`email` LIKE "%' . mysql_escape_string($searchstring) . '%")) ';
      if ($filterlist == -1) {
        $query = $query . 'AND `mailing_lists` = "" ';
      }
      else if ($filterlist > 0) {
        $query = $query . 'AND (FIND_IN_SET("'.mysql_escape_string($filterlist).'", `mailing_lists`) > 0) ';
      }
      $orderby = $this->_buildContentOrderBy();
      $query .= $orderby;

      $subs = $this->_getList( $query , $limitstart, $limit);

      return $subs;
    }

    function getAllSubs() {
        $db =& JFactory::getDBO();

        $query = 'SELECT * FROM `#__nspro_subs`';
        $orderby = $this->_buildContentOrderBy();
        $query .= ' '.$orderby;

        $db->setQuery($query);

        $subs = $db->loadObjectList();

        return $subs;
    }

    function getSubsCount($filterlist) {
        $db =& JFactory::getDBO();

        $query = 'SELECT COUNT(`id`) FROM `#__nspro_subs` ';
        if ($filterlist == -1) {
          $query = $query . 'WHERE `mailing_lists` = ""';
        }
        else if ($filterlist > 0) {
          $query = $query . 'WHERE (FIND_IN_SET("'.mysql_escape_string($filterlist).'", `mailing_lists`) > 0)';
        }

        $db->setQuery( $query );
        $sCount = $db->loadResult();

        return $sCount;
    }

    function getSubsCountSearch($searchstring, $filterlist) {
        $db =& JFactory::getDBO();

        $query = 'SELECT COUNT(`id`) FROM `#__nspro_subs` ';
        $query = $query . 'WHERE ((`name` LIKE "%' . mysql_escape_string($searchstring) . '%") OR (`email` LIKE "%' . mysql_escape_string($searchstring) . '%")) ';
        if ($filterlist == -1) {
          $query = $query . 'AND (`mailing_lists` = "")';
        }
        else if ($filterlist > 0) {
          $query = $query . 'AND (FIND_IN_SET("'.mysql_escape_string($filterlist).'", `mailing_lists`) > 0)';
        }

        $db->setQuery( $query );
        $sCount = $db->loadResult();

        return $sCount;
    }

    function store()
    {
        $db =& JFactory::getDBO();
        $row =& $this->getTable('nssubs');
        $data = JRequest::get( 'post' );
        $data["datetime"] = date('Y-m-d H:i:s', strtotime($data["datetime"]));

        if (!$row->bind($data)) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        if (!$row->check()) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        if (!$row->store()) {
            $this->setError( $row->getErrorMsg() );
            return false;
        }

        // EXTRA FIELDS
        if (!function_exists('SaveExtraFields')) {
          include('components/com_nspro/lib.php');
        }
        $subid = $data['id'];
        if ($subid == '0') {
          $subid = $db->insertid();
        }
        $saved = SaveExtraFields($subid, $data);
        if ($saved != true) {
          return $saved;
        }

        return true;
    }

    function delete() {
      $db =& JFactory::getDBO();
      $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

      $row =& $this->getTable('nssubs');

      if (count( $cids )) {
        foreach($cids as $cid) {
          if (!$row->delete( $cid )) {
            $this->setError( $row->getErrorMsg() );
            return false;
          }
          else {
            $query = 'DELETE FROM `#__nspro_field_values` WHERE `subscriber_id`="'.mysql_escape_string($cid).'"';
            $db->setQuery($query);
            $db->query();
          }
        }
      }
      return true;
    }
    
    function massconfirm() {
      $db =& JFactory::getDBO();
      $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

      if (count( $cids )) {
        foreach($cids as $cid) {
          $query = 'UPDATE `#__nspro_subs` SET `confirmed` = true WHERE `id`="'.mysql_escape_string($cid).'"';
          $db->setQuery($query);
          if (!$db->query()) {
            $this->setError( $row->getErrorMsg() );
            return false;
          }
        }
      }
      return true;
    }
    
    function massunconfirm() {
      $db =& JFactory::getDBO();
      $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

      if (count( $cids )) {
        foreach($cids as $cid) {
          $query = 'UPDATE `#__nspro_subs` SET `confirmed` = false WHERE `id`="'.mysql_escape_string($cid).'"';
          $db->setQuery($query);
          if (!$db->query()) {
            $this->setError( $row->getErrorMsg() );
            return false;
          }
        }
      }
      return true;
    }

    function insertLine($db, $iname, $iemail, $idatetime, $iconfirmed, $ilists) {
      $query = 'INSERT INTO `#__nspro_subs` (`name`, `email`, `datetime`, `confirmed`, `mailing_lists`)'.
               'VALUES ("'.mysql_escape_string($iname).'", "'.
                           mysql_escape_string($iemail).'", "'.
                           mysql_escape_string($idatetime).'", "'.
                           mysql_escape_string($iconfirmed).'", "'.
                           mysql_escape_string($ilists).'")';
      $db->setQuery( $query );
      return $db->query();

    }

    function importFromNSFile($filename) {
       
      $handle = fopen($filename, "r");
      $contents = fread($handle, filesize($filename));
      fclose($handle);

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $delimtype = $params->get( 'import_ns_delimiter', '0' );
      if ($delimtype == '1') {
        $startDelim = '<';
        $endDelim   = '>';
      }
      else if ($delimtype == '2') {
        $startDelim = '[';
        $endDelim   = ']';
      }
      else if ($delimtype == '3') {
        $startDelim = '{';
        $endDelim   = '}';
      }
      else {
        $startDelim = '(';
        $endDelim   = ')';
      }

      $atleastone = false;
      $startChar = 0;
      $fromChar = JString::strpos($contents, $startDelim);
      $icount = 0;
      $db =& JFactory::getDBO();
      while ($fromChar !== false) {
        $myRecipientsName = JString::substr($contents, $startChar, $fromChar - $startChar - 1);
        $toChar = JString::strpos($contents, $endDelim, $fromChar);
        $myRecipient = JString::substr($contents, $fromChar+1, $toChar-$fromChar-1);

        $atleastone = true;
        $added = $this->insertLine($db, $myRecipientsName, $myRecipient, date('Y-m-d H:i:s'), 1, '');
        if ($added == true) { 
          $icount = $icount + 1;
        }

        $fromChar = JString::strpos($contents, $startDelim, $toChar);
        $startChar = $toChar+2;
      }

      if ($atleastone == false) {
        return 'No subscribers found.';
      }

      return $icount;

    }

    function importCSV($filename) {

      if (!function_exists('str_getcsv')) {
        include('components/com_nspro/extrafunctions.php');
      }
      include('components/com_nspro/lib.php');

      // get file contents
      $contents = file_get_contents($filename);

      // get component parameters
      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );      
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $idelim = $params->get( 'import_delimiter', ';' );
      $ief = $params->get('import_extra_fields', '1');

      // replace all content line separators with a simple line break
      $contents = preg_replace('/\r\n|\r/', "\n", $contents);

      // each line is supposed to be a subscriber, except for # ones.
      $lines = explode("\n", $contents);

      $atleastone = false;
      $icount = 0;
      $db =& JFactory::getDBO();
      foreach ($lines as $line) {
        if (($line == '') || ($line[0] == '#')) {
          continue;
        }
        if (function_exists('str_getcsv')) {
          $values = str_getcsv($line, $idelim);
        }
        else {
          $values = explode($idelim, $line);
          for($i = 0; $i < count($values); $i++) {
            $values[$i] = trim($values[$i]);
            $values[$i] = trim($values[$i], '"');
          }
        }
        $atleastone = true;
        $values[2] = date('Y-m-d H:i:s', strtotime($values[2]));
        if (($values[3] == 'Y') || ($values[3] == 'y') ||
            ($values[3] == 'Yes') || ($values[3] == 'yes') ||
            ($values[3] == 'T') || ($values[3] == 'True') ||
            ($values[3] == 't') || ($values[3] == 'true') ||
            ($values[3] == '1') || ($values[3] == 'confirmed')) {
          $values[3] = '1';
        }
        else {
          $values[3] = '0';
        }
        // INSERT THE SUBSCRIBER
        ////                              NAME       EMAIL     DATETIME    CONFIRMED  MAILINGLISTS
        $added = $this->insertLine($db, $values[0], $values[1], $values[2], $values[3], $values[4]);
        if ($added == true) { 
          $icount = $icount + 1;
        }
        
        $minsertid = $db->insertid();
        
        $wief = (($ief == '1') ? " WHERE `published` = true" : "");

        if ($ief != '0') {
          // INSERT THE EXTRA FIELD VALUES
          $db->setQuery('SELECT * FROM `#__nspro_fields`'.$wief.' ORDER BY `id`');
          $fields = $db->loadObjectList();

          if (count($fields) > 0) {
            for($j = 0; $j < count($fields); $j++) {
              if ((isset($values[$j+5])) && ($values[$j+5] != '')) {
                $this->insertFieldValue($minsertid, $fields[$j], $values[$j+5]);
              }
            }
          }
        }
      }

      if ($atleastone == false) {
        return JText::_('No subscribers found.');
      }

      return $icount;

    }

    function insertFieldValue($subid, $field, $value) {
      $db =& JFactory::getDBO();

      switch($field->fieldtype) {
        case '2':
          if (($value == 'Y') || ($value == 'Yes') ||
              ($value == 'y') || ($value == 'yes') ||
              ($value == 'T') || ($value == 'True') ||
              ($value == 't') || ($value == 'true') ||
              ($value == '1') || ($value == 'confirmed')) {
            $value = '1';
          }
          else {
            $value = '0';
          }
        break;
        case '3';
        case '4';
        case '6';
          $value = JString::str_ireplace('"', '', $value);
        break;
      }

      $query = 'INSERT INTO `#__nspro_field_values` (`subscriber_id`, `field_id`, `value`) ';
      $query .= 'VALUES("'.mysql_escape_string($subid).'", "'.mysql_escape_string($field->id).'", "'.mysql_escape_string($value).'")';
      $db->setQuery($query);
      $db->query();
    }

    function importFromTextFile($filename) {
      $imported = $this->importCSV($filename);
      return $imported;
    }

    function importFromExcelFile($filename) {
      $imported = $this->importCSV($filename);
      return $imported;
    }

    function importFromJoomlaUsers() {
      $db =& JFactory::getDBO();

      $query = 'SELECT * FROM `#__users` ORDER BY `id`';

      $db->setQuery($query);

      $users = $db->loadObjectList();

      $msubs = $this->getAllSubs();

      $icount = 0;
      $db =& JFactory::getDBO();
      foreach($users as $user) {
        $found = false;
        for ($i = 0; $i < count($msubs); $i++) {
          if ($msubs[$i]->email == $user->email) {
            $found = true;
            break;
          }
        }
        if (!$found) {
          $added = $this->insertLine($db, $user->name, $user->email, $user->registerDate, 1, '');
					if ($added == true) { 
						$icount = $icount + 1;
					}
        }
      }

      return $icount;
    }

    function _buildContentOrderBy() {
      //global $mainframe, $option;
      $mainframe = JFactory::getApplication();
      $option = JRequest::getCmd('option');      

      $orderby = '';
      $filter_order     = $this->getState('filter_order');
      $filter_order_Dir = $this->getState('filter_order_Dir');

      if(!empty($filter_order) && !empty($filter_order_Dir) ){
        $orderby = ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
      }

      return $orderby;
    }

}
?>